interface TreeNode {
  id: number
  label?: string // 节点显示名称
  children: TreeNode[] // 子节点（始终为数组）
  value?: any // 可选：原始值（非对象类型时存储）
  disabled?: boolean
  path: string
}

class JsonTool {
  private id = 0
  transfromJson(json: any, key = 'root', path = '$'): TreeNode {
    // 1. 原始值（null、boolean、number、string）
    if (json === null || typeof json !== 'object') {
      return this.transFromValue(json, key, path)
    }
    // 2. 数组
    if (Array.isArray(json)) {
      return {
        id: ++this.id,
        label: key,
        children: this.transFromArray(json, key, path),
        path: `${path}.*`,
      }
    }
    // 3. 普通对象
    const children: TreeNode[] = []
    for (const [k, v] of Object.entries(json)) {
      children.push(this.transfromJson(v, k, `${path}.${k}`))
    }
    return {
      id: ++this.id,
      label: key,
      children,
      path,
    }
  }

  transFromValue(valueToTransform: any, keyForValue: string, path: string): TreeNode {
    return {
      id: ++this.id,
      label: `${keyForValue}: ${valueToTransform}`,
      children: [],
      disabled: true,
      path,
    }
  }

  transFromArray(json: any, key: string, path: string): TreeNode[] {
    const children: TreeNode[] = []
    for (const [idx, v] of Object.entries(json)) {
      children.push(this.transfromJson(v, `${key}[${idx}]`, `${path}[${idx}]`))
    }
    return children
  }

  transFromObject(json: any, key: string, path: string): TreeNode {
    const nodePath = `${path}.${key}`
    const children: TreeNode[] = []
    for (const [k, v] of Object.entries(json)) {
      children.push(this.transfromJson(v, k, `${nodePath}.${k}`))
    }
    return { id: ++this.id, label: key, children, path: nodePath }
  }
}

/**
 * 任意 JSON → 根节点为数组的树
 * @param json 任意 JSON 值
 * @param key  当前字段名（递归用，外部调用可忽略）
 */
function jsonToTree(json: unknown, key = 'root'): TreeNode {
  const tool = new JsonTool()
  return tool.transfromJson(json, key)
}

export default jsonToTree
